package com.bc004346.travelus;

import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.bc004346.travelus.DataAccess.AirportDataProvider;
import com.bc004346.travelus.Model.Domain.FlightSearchParams;
import com.bc004346.travelus.Utility.Utility;

import static com.bc004346.travelus.Utility.Utility.FLIGHT_SEARCH_PARAMS;
import static com.bc004346.travelus.Utility.Utility.log;
import static com.bc004346.travelus.Utility.Utility.onActivityStart;
import static com.bc004346.travelus.Utility.Utility.onActivityStop;

/**
 * Created by Renats on 6/29/2014.
 * This handles airport lookup list view
 */
public class SearchableActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    ListView mListViewAirports;
    SimpleCursorAdapter mCursorAdapter;

    //<editor-fold desc="Overrides">


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        FlightSearchParams flightSearchParams = new FlightSearchParams();
        setContentView(R.layout.activity_airport_lookup);
        mListViewAirports = (ListView) findViewById(R.id.activity_airport_lookup_list_view);

        // Setting item click listener
        mListViewAirports.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getApplicationContext(), BookTravelActivity.class);
                Uri data = Uri.withAppendedPath(AirportDataProvider.CONTENT_URI, String.valueOf(id));
                intent.setData(data);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);

            }
        });

        // Getting the intent that invoked this activity
        Intent originalIntent = getIntent();
        String result = originalIntent.getData().getLastPathSegment().toUpperCase();
        Bundle appData = originalIntent.getBundleExtra(SearchManager.APP_DATA);
        if (appData != null)
            flightSearchParams = (FlightSearchParams) appData.getSerializable(FLIGHT_SEARCH_PARAMS);

        // If this activity is invoked by selecting an item from Suggestion of Search dialog or
        // from listview of SearchActivity
        if (originalIntent.getAction().equals(Intent.ACTION_VIEW)) {

            Intent intent = new Intent(this, BookTravelActivity.class);
            if (flightSearchParams.getAirportLookupToken() == FlightSearchParams.Flag.Origin)
                flightSearchParams.setOrigin(result);
            else
                flightSearchParams.setDestination(result);
            intent.putExtra(FLIGHT_SEARCH_PARAMS, flightSearchParams);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();


        } else if (originalIntent.getAction().equals(Intent.ACTION_SEARCH)) { // If this activity is invoked, when user presses "Go" in the Keyboard of Search Dialog
            String query = originalIntent.getStringExtra(SearchManager.QUERY);
            doSearch(query);
        }

    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        Uri uri = AirportDataProvider.CONTENT_URI;
        return new CursorLoader(getBaseContext(), uri, null, null, new String[]{bundle.getString("query")}, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    @Override
    protected void onStart() {
        try {
            super.onStart();
            onActivityStart(this);
        } catch (Exception e) {
            log(e, this);
        }
    }

    @Override
    protected void onStop() {
        try {
            super.onStop();
            Utility.onStop(this);
            onActivityStop(this);
        } catch (Exception e) {
            log(e, this);
        }
    }
    //</editor-fold>


    private void doSearch(String query) {
        Bundle data = new Bundle();
        data.putString("query", query);

        // Invoking onCreateLoader() in non-ui thread
        getSupportLoaderManager().initLoader(1, data, this);
    }
}
